package com.cfm880.basicpipeuse;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "PipeExample";
    private EditText editText;

    PipedReader r;
    PipedWriter w;

    private Thread workerThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        r = new PipedReader();
        w = new PipedWriter();
        try {
            w.connect(r);
        } catch (IOException e){
            e.printStackTrace();
        }
        setContentView(R.layout.activity_main);

        editText = (EditText)findViewById(R.id.editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                try {

                    // only handle addition of characters
                    if (count > before){
                        // Write the last entered character to hte pipe
                        w.write(s.subSequence(before, count).toString());
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        workerThread = new Thread(new TextHandleTask(r));
        workerThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        workerThread.interrupt();
        try {
            r.close();
            w.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    private static class TextHandleTask implements Runnable{
        private final PipedReader reader;

        public TextHandleTask(PipedReader reader) {
            this.reader = reader;
        }

        @Override
        public void run() {
            while (Thread.currentThread().isInterrupted()){
                try{
                    int i;
                    // Add text processing logic here
                    while ((i = reader.read()) != -1){
                        char c = (char) i;
                        Log.d(TAG, "char = " + c);
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
